/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.aggregator.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.ourgrid.aggregator.AggregatorConstants;
import org.ourgrid.aggregator.dao.AggregatorDAO;
import org.ourgrid.aggregator.dao.AggregatorPeerStatusProvider;
import org.ourgrid.aggregator.interfaces.Aggregator;
import org.ourgrid.common.interfaces.status.ConsumerInfo;
import org.ourgrid.common.interfaces.status.LocalConsumerInfo;
import org.ourgrid.common.interfaces.status.NetworkOfFavorsStatus;
import org.ourgrid.common.interfaces.status.PeerStatusProvider;
import org.ourgrid.common.interfaces.status.RemoteWorkerInfo;
import org.ourgrid.common.interfaces.to.TrustyCommunity;
import org.ourgrid.common.interfaces.to.UserInfo;
import org.ourgrid.common.interfaces.to.WorkerInfo;
import org.ourgrid.common.statistics.beans.ds.DS_PeerStatusChange;
import org.ourgrid.peer.PeerConstants;
import org.ourgrid.peer.status.PeerCompleteHistoryStatus;
import org.ourgrid.peer.status.PeerCompleteStatus;

import br.edu.ufcg.lsd.commune.Module;
import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.identification.ServiceID;

/**
 * @author alan
 *
 */
public class AggregatorController implements Aggregator {

	private ServiceManager serviceManager;

	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public void hereIsCompleteStatus(ServiceID statusProviderServiceID,
			PeerCompleteStatus completeStatus) {
		// TODO Auto-generated method stub
		
	}


	public void hereIsCompleteHistoryStatus(ServiceID statusProviderServiceID,
			PeerCompleteHistoryStatus completeStatus, long time) {
		
		AggregatorDAO dao = serviceManager.getDAO(AggregatorDAO.class);
		
		AggregatorPeerStatusProvider provider = dao.getProvider(statusProviderServiceID);
		if (provider != null) {
			provider.setMustUpdate(true);
		}

		try {
			dao.addCompleteHistoryStatus(completeStatus, statusProviderServiceID.getContainerID().getUserAtServer());
			if (provider != null) {
				provider.setLastUpdateTime(time);
			}
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
		
	}
	
	public void hereIsLocalConsumersStatus(ServiceID statusProviderServiceID,
			List<LocalConsumerInfo> localConsumers) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsLocalWorkersStatus(ServiceID statusProviderServiceID,
			List<WorkerInfo> localWorkers) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsNetworkOfFavorsStatus(ServiceID statusProviderServiceID,
			NetworkOfFavorsStatus nofStatus) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsRemoteConsumersStatus(ServiceID statusProviderServiceID,
			List<ConsumerInfo> remoteConsumers) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsRemoteWorkersStatus(ServiceID statusProviderServiceID,
			List<RemoteWorkerInfo> remoteWorkers) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsTrustStatus(ServiceID statusProviderServiceID,
			List<TrustyCommunity> trustInfo) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsUsersStatus(ServiceID statusProviderServiceID,
			List<UserInfo> usersInfo) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsRemoteWorkerProviderList(
			List<ServiceID> workerProviders) {
		
	}
	public void hereIsConfiguration(Map<String, String> configuration) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsUpTime(long uptime) {
		// TODO Auto-generated method stub
		
	}

	public void hereIsStatusProviderList(List<String> providers) {
		
		AggregatorDAO aggregatorDAO = serviceManager.getDAO(AggregatorDAO.class);
		
		Set<ServiceID> oldProviders = new HashSet<ServiceID>(aggregatorDAO.getCurrentProvidersIds());
		
		for (String providerAddress : providers) {
			
			String[ ] splitAddress = providerAddress.split("@");
			
			ServiceID providerID = new ServiceID(splitAddress[0], splitAddress[1], PeerConstants.MODULE_NAME, Module.CONTROL_OBJECT_NAME);
			
			boolean isCurrent = oldProviders.remove(providerID);
			
			if (isCurrent) {
				requestForHistoryStatus(aggregatorDAO.getProvider(providerID));
			} else {
				serviceManager.registerInterest(AggregatorConstants.OBJECT_NAME, 
						providerID.toString(), PeerStatusProvider.class);
			}
			
		}
		
		for (ServiceID oldProviderServiceID : oldProviders) {
			removeProvider(oldProviderServiceID);
		}
		
	}

	private void removeProvider(ServiceID providerServiceID) {
		AggregatorPeerStatusProvider aggProvider = serviceManager.getDAO(
				AggregatorDAO.class).removeProvider(providerServiceID);
		if (aggProvider != null && aggProvider.getProvider() != null) {
			serviceManager.release(aggProvider);
		}
	}

	public void hereIsPeerStatusChangeHistory(List<DS_PeerStatusChange> statusChanges, long since) {
		AggregatorDAO dao = serviceManager.getDAO(AggregatorDAO.class);
		try {
			dao.savePeersStatusChanges(statusChanges);
			dao.setPeerStatusChangeLastUpdate(since);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private void requestForHistoryStatus(AggregatorPeerStatusProvider aggProvider) {
		if (aggProvider.mustUpdate()) {
			aggProvider.getProvider().getCompleteHistoryStatus(this, aggProvider.getLastUpdateTime());
			aggProvider.setMustUpdate(false);
		}
	}
	
	@RecoveryNotification
	public void peerStatusProviderIsUp(PeerStatusProvider provider, DeploymentID providerId) {
		AggregatorPeerStatusProvider aggProvider = new AggregatorPeerStatusProvider(
				providerId.getServiceID(), provider);
		serviceManager.getDAO(AggregatorDAO.class).putProvider(providerId.getServiceID(), aggProvider);
		requestForHistoryStatus(aggProvider);
	}
	

	@FailureNotification
	public void peerStatusProviderIsDown(PeerStatusProvider provider, DeploymentID providerId) {
		removeProvider(providerId.getServiceID());
	}
}